package concurrentpractice;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.Arrays;
import org.junit.Test;

/**
 * 非常慢，耐心等输出结果
 */
public class PipedStreamSolution {

  @Test
  public void verifyPipedStream() throws InterruptedException, IOException {

    final PipedInputStream numberPrinterInputStream = new PipedInputStream();
    final PipedOutputStream numberPrinterOutputStream = new PipedOutputStream();
    final PipedInputStream letterPrinterInputStream = new PipedInputStream();
    final PipedOutputStream letterPrinterOutputStream = new PipedOutputStream();

    numberPrinterOutputStream.connect(letterPrinterInputStream);
    letterPrinterOutputStream.connect(numberPrinterInputStream);

    final byte[] GO_MSG = "Go".getBytes();

    Thread numberPrintThread = new Thread(() -> {
      byte[] inArr = new byte[2];
      for (int i = 1; i < 52; i = i + 2) {
        try {
          for (int j = 0; j < 2; j++) {
            System.out.print(i + j);
          }
          numberPrinterOutputStream.write(GO_MSG);
          do {
            numberPrinterInputStream.read(inArr);
          } while (!Arrays.equals(GO_MSG, inArr));
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    });
    Thread letterPrintThread = new Thread(() -> {
      byte[] inArr = new byte[2];
      for (char i = 'A'; i <= 'Z'; i++) {
        try {
          do {
            letterPrinterInputStream.read(inArr);
          } while (!Arrays.equals(GO_MSG, inArr));
          System.out.print(i);
          letterPrinterOutputStream.write(GO_MSG);
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    });

    numberPrintThread.start();
    letterPrintThread.start();

    numberPrintThread.join();
    letterPrintThread.join();

    numberPrinterInputStream.close();
    numberPrinterOutputStream.close();
    letterPrinterInputStream.close();
    letterPrinterOutputStream.close();
  }
}
